﻿using System;
using System.Collections.Generic;
using System.Linq;
using org.se.fs.presenter.IView.Template;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View
{
    public class BranchLists : Template.ViewLists<Domain.Branch>, IViewLists<Domain.Branch>
    {
        private readonly IFormLists _view;
        private readonly ITask.IBranch _task;

        public BranchLists(IFormLists view) : this(view, new Task.Context.Branch()) { }

        public BranchLists(IFormLists view, ITask.IBranch task)
        {
            _view = view;
            _task = task;
        }

        void TaskOnFetchLists(object source, FormEvent e)
        {
            if (!e.IsSuccess)
            {
                _view.Lists = null;
                _view.StatusLists = "Result: 0 records";
                return;
            }

            Lists = (IList<Domain.Branch>)e.Value;
            DisplayData();
        }

        public void Initialize()
        {
            Lists = new List<Domain.Branch>();
            _task.OnFetchLists += TaskOnFetchLists;
            _task.OnDelete += TaskOnDelete;
            _task.FetchLists(null);
        }

        void TaskOnDelete(object source, FormEvent e)
        {
            TriggerDelete(new FormEvent(true) { Exception = e.Exception });

            if (!e.IsSuccess)
                return;

            var data = (Domain.Branch)e.Value;
            var a = (Lists.Where(b => b.Id.Equals(data.Id))).First();
            Lists.Remove(a);
            DisplayData();
        }

        public void TaskOnFetch(object source, FormEvent e)
        {
        }

        public void TaskOnToggle(object source, FormEvent e)
        {
        }

        public void Search()
        {
        }

        public override void DisplayData()
        {
            _view.StatusLists = string.Format("Result: {0} records", Lists.Count);

            if (Lists.Count.Equals(0))
                _view.Lists = null;

            Lists = Lists.OrderBy(a => a.Name).OrderBy(a => a.Code).ToList();
            _view.Lists = (Lists.Select(a => new {a.Name, a.Code, a.Address})).ToList();
        }

        public void Toggle(UInt16 index)
        {
        }

        public void Modify(Domain.Branch data)
        {
            if (data == null)
                return;
            var a = (Lists.Where(b => b.Id.Equals(data.Id))).First();
            var index = Lists.IndexOf(a);
            Lists[index] = data;
            DisplayData();
        }

        public void Remove(Domain.Branch data)
        {
            if (data == null)
                return;
            _task.Delete(data);
        }
    }
}
